package com.king.headline.util.encry;


import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

public class DesEncrypter {
	
	private static final String PASSPHRASE = "t33kata";
    
    // 8-byte Salt
    private static final byte[] salt = {
        (byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
        (byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03
    };

    // Iteration count
    private static final int iterationCount = 19;
    
	private Cipher ecipher;
    private Cipher dcipher;

    public static DesEncrypter getInstance() {
		return new DesEncrypter();
    }
    
    private DesEncrypter() {
    	super();
    	setup();
    }

    public synchronized void setup() {
//    	if(Security.getProvider("BC") == null) {
//			BouncyCastleProvider bcProv = new BouncyCastleProvider();
//			if(firstProvider) {
//				Security.insertProviderAt(bcProv, 1);
//			} else {
//				Security.addProvider(bcProv);
//			}
//    	}
    	try {
            // Create the key
            KeySpec keySpec = new PBEKeySpec(PASSPHRASE.toCharArray(), salt, iterationCount);
            SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
            ecipher = Cipher.getInstance(key.getAlgorithm());
            dcipher = Cipher.getInstance(key.getAlgorithm());

            // Prepare the parameter to the ciphers
            AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);

            // Create the ciphers
            ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
            dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
        } catch (Exception e) {
        	//log.error("setup failed: ",e);
        }    	
    }
    
    private Cipher getEcipher(String pass){
    	Cipher ecipher = null;
		try {
			if(pass != null) pass += PASSPHRASE;
			else pass = PASSPHRASE;
			KeySpec keySpec = new PBEKeySpec(PASSPHRASE.toCharArray(), salt, iterationCount);
			SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
			ecipher = Cipher.getInstance(key.getAlgorithm());
			// Prepare the parameter to the ciphers
			AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
			// Create the ciphers
			ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			e.printStackTrace();
		}
        return ecipher;
    }
    
    private Cipher getDcipher(String pass){
    	Cipher dcipher = null;
		try {
			if(pass != null) pass += PASSPHRASE;
			else pass = PASSPHRASE;
			KeySpec keySpec = new PBEKeySpec(PASSPHRASE.toCharArray(), salt, iterationCount);
			SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
			dcipher = Cipher.getInstance(key.getAlgorithm());
			// Prepare the parameter to the ciphers
			AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
			// Create the ciphers
			dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			e.printStackTrace();
		}
        return dcipher;
    }    
    
    
    
    public String encrypt(String str) throws Exception {
        try {
            // Encode the string into bytes using utf-8
            byte[] utf8 = str.getBytes("UTF8");

            // Encrypt
            byte[] enc = ecipher.doFinal(utf8);

            // Encode HEXEncode to get bytes
            return new String(Hex.encode(enc));        
       } catch (Exception e) {
        	throw e;
        }
    }

    public String encrypt(String str, String key) throws Exception {
        try {
            // Encode the string into bytes using utf-8
            byte[] utf8 = str.getBytes("UTF8");

            // Encrypt
            byte[] enc = getEcipher(key).doFinal(utf8);

            // Encode HEXEncode to get bytes
            return new String(Hex.encode(enc));        
       } catch (Exception e) {
        	throw e;
        }
    }    
    
    public String decrypt(String str) throws Exception {
    	byte[] decDebug = new byte[0];
        try {
            // Decode HEXEncode to get bytes        	
            byte[] dec = Hex.decode(str);
            decDebug = new byte[dec.length];
            System.arraycopy(dec, 0, decDebug, 0, dec.length);
            byte[] utf8 = dcipher.doFinal(dec);
            // Decode using utf-8
            return new String(utf8, "UTF8");
        } catch (Exception e) {
        	String decString = "Bytes: ";
			  for (byte cur : decDebug) {
				  decString += (new Byte (cur)).toString() + " ";
			  }
        	 String s = "Bytes: ";
        	 byte[] dec = Hex.decode(str);
			  for (byte cur : dec) {
				  s += (new Byte (cur)).toString() + " ";
			  }
        	throw e;
        }
    }
    
    public String decrypt(String str, String key) throws Exception {
    	byte[] decDebug = new byte[0];
        try {
            // Decode HEXEncode to get bytes        	
            byte[] dec = Hex.decode(str);
            decDebug = new byte[dec.length];
            System.arraycopy(dec, 0, decDebug, 0, dec.length);
            byte[] utf8 = getDcipher(key).doFinal(dec);
            // Decode using utf-8
            return new String(utf8, "UTF8");
        } catch (Exception e) {
        	String decString = "Bytes: ";
			  for (byte cur : decDebug) {
				  decString += (new Byte (cur)).toString() + " ";
			  }
        	 String s = "Bytes: ";
        	 byte[] dec = Hex.decode(str);
			  for (byte cur : dec) {
				  s += (new Byte (cur)).toString() + " ";
			  }
        	throw e;
        }
    }    
    
    public synchronized String decryptThreadSafe(String str) throws Exception {
    	byte[] decDebug = new byte[0];
        try {
            // Decode HEXEncode to get bytes        	
            byte[] dec = Hex.decode(str);
            decDebug = new byte[dec.length];
            System.arraycopy(dec, 0, decDebug, 0, dec.length);
            byte[] utf8 = dcipher.doFinal(dec);

            
            // Decode using utf-8
            return new String(utf8, "UTF8");
        } catch (Exception e) {
        	String decString = "Bytes: ";
			  for (byte cur : decDebug) {
				  decString += (new Byte (cur)).toString() + " ";
			  }
        	 String s = "Bytes: ";
        	 byte[] dec = Hex.decode(str);
			  for (byte cur : dec) {
				  s += (new Byte (cur)).toString() + " ";
			  }
        	throw e;
        }
    }

}

